/**
 * 
 */
package com.neal.service.securities.authrity;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.neal.domain.securities.User;
import com.neal.repositories.securities.UserRepository;


/**
 * @author Neal
 * @version 1.0
 * @description
 */
public class UserDetailServiceBean implements UserDetailsService{

	@Autowired
	private UserRepository userRepository;
	
	
	/* (non-Javadoc)
	 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		User user = userRepository.findByUserName(userName);
		
		if(user==null){
			throw new UsernameNotFoundException(userName + " is not exist");
		}
		
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole().getName()));
		
		org.springframework.security.core.userdetails.User userDetail = new org.springframework.security.core.userdetails.User(
				userName, user.getPassword(), grantedAuthorities); 
		
		return userDetail;
	}

}
